package logic

import (
	"context"
	"fmt"
	"toy/models/mysql"

	"toy/toyrpc/internal/svc"
	"toy/toyrpc/toyrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopAddLogic {
	return &ShopAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShopAddLogic) ShopAdd(in *toyrpc.ShopAddRequest) (*toyrpc.ShopAddResponse, error) {
	// todo: add your logic here and delete this line
	begin := mysql.DB.Debug().Begin()
	var class mysql.Class
	begin.Where("name = ?", in.ClassName).Find(&class)
	if class.ID == 0 {
		class = mysql.Class{
			Name: in.ClassName,
		}
		err := begin.Create(&class).Error
		if err != nil {
			return nil, fmt.Errorf("分类添加失败")
			begin.Rollback()
		}
	}
	var brand mysql.Brand
	begin.Where("name = ?", in.BrandName).Find(&brand)
	if brand.ID == 0 {
		brand = mysql.Brand{
			Name: in.BrandName,
		}
		err := begin.Create(&brand).Error
		if err != nil {
			return nil, fmt.Errorf("品牌添加失败")
			begin.Rollback()
		}
	}
	var shop = mysql.Shop{
		Name:    in.Name,
		Price:   float64(in.Price),
		Img:     in.Img,
		ClassId: int(class.ID),
		BrandId: int(brand.ID),
	}
	err := begin.Create(&shop).Error
	if err != nil {
		return nil, fmt.Errorf("商品添加失败")
		begin.Rollback()
	}
	begin.Commit()
	return &toyrpc.ShopAddResponse{
		ShopId: int64(shop.ID),
	}, nil
}
